package com.winit.indexing.repository;

import com.datastax.driver.core.querybuilder.Delete;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.datastax.driver.core.querybuilder.Update;
import com.winit.indexing.model.Indexing;
import com.winit.indexing.model.IndexingId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.stereotype.Repository;

import javax.management.Query;
import java.util.List;

@Repository
public class IndexingRepositoryExtImpl implements IndexingRepositoryExt {

    @Autowired
    private CassandraOperations cassandraOperations;

    @Override
    public int updateExistPropertyById(Indexing indexing) {
        Update update = QueryBuilder.update("matrix_indexing");
        update.where(QueryBuilder.eq("index_group", indexing.getId().getIndexGroup()));
        update.where(QueryBuilder.eq("filter_tag", indexing.getId().getFilterTag()));
        if (null != indexing.getIndexMap()){
            update.with(QueryBuilder.set("index_map", indexing.getIndexMap()));
        }
        cassandraOperations.execute(update);
        return 1;
    }

    @Override
    public List<String> findFilterTagByIndexGroup(String indexGroup) {
        Select select = QueryBuilder.select("filter_tag").from("matrix_indexing");
        select.where(QueryBuilder.eq("index_group", indexGroup));
        return cassandraOperations.select(select, String.class);
    }

    @Override
    public List<Indexing> findByIndexGroup(String indexGroup) {
        return null;
    }

    @Override
    public boolean deleteByCondition(IndexingId indexingId) {
        Delete delete = QueryBuilder.delete().from("matrix_indexing");
        if (indexingId.getFilterTag() != null){
            delete.where(QueryBuilder.eq("filter_tag", indexingId.getFilterTag()));
        }
        if (indexingId.getIndexGroup() != null){
            delete.where(QueryBuilder.eq("index_group", indexingId.getIndexGroup()));
        }
        cassandraOperations.execute(delete);
        return true;
    }
}
